package com.xuecheng.content.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.ValidationGroups;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.dto.CourseTeacherDTO;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.CourseTeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    // 根据ID查询师资列表
    @Override
    public List<CourseTeacher> getIdByCourseTeacherList(Long courseId) {
        LambdaQueryWrapper<CourseTeacher> tcLambda = new LambdaQueryWrapper<>();
        tcLambda.eq(courseId != null,CourseTeacher::getCourseId,courseId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(tcLambda);
        return courseTeachers;
    }

    // 修改,增加课程老师
    @Override
    public CourseTeacher saveAndUpdate(CourseTeacherDTO courseTeacherDTO) {
        Long id = courseTeacherDTO.getId();
        CourseTeacher courseTeacher = new CourseTeacher();
        if (id == null) {
            // 新增
            BeanUtils.copyProperties(courseTeacherDTO,courseTeacher);
            courseTeacher.setCreateDate(LocalDateTime.now());
            try {
                // SQLIntegrityConstraintViolationException老师重复时报此异常,数据库约束
                courseTeacherMapper.insert(courseTeacher);
            } catch (Exception e) {
                XueChengPlusException.cast("课程老师不能重复");
            }
        } else {
            // 修改
            BeanUtils.copyProperties(courseTeacherDTO, courseTeacher);
            courseTeacherMapper.updateById(courseTeacher);
        }
        return courseTeacher;
    }

    // 删除老师
    @Override
    public void deleteCourseTeacher(Long courseId, Long id) {
        LambdaQueryWrapper<CourseTeacher> lambaDelete = new LambdaQueryWrapper<>();
        lambaDelete.eq(courseId!=null,CourseTeacher::getCourseId,courseId);
        lambaDelete.eq(id!=null,CourseTeacher::getId,id);
        courseTeacherMapper.delete(lambaDelete);
    }
}
